package cn.dengta.webapp.im.entity;

import java.util.Date;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import cn.dengta.common.model.TimeInterval;
import cn.dengta.common.web.Client;
import cn.dengta.webapp.base.entity.TimeBasedEntity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import me.codeplayer.util.EasyDate;

/**
 * 登录记录
 */

@Getter
@Setter
@Accessors(chain = true)
@TableName("im_ws_user_login_log")
public class WsUserLoginLog extends TimeBasedEntity {

	/** 用户ID */
	private Long userId;
	/** 本次登录时间 */
	private Date loginTime;
	/** 本次退出时间 */
	private Date logoutTime;
	/** 所在机器channel_id */
	private String channelId;
	/** 客户端IP */
	private String clientIp;
	/** 节点IP */
	private String nodeIp;
	/** 用户登录终端 */
	private Client client;
	/** 本次登录的持续时间（秒） */
	private Long duration;

	public transient Long agentId;

	/** 当log来源于云信登录回调时,channelId固定为此常量 */
	public static final String CHANNEL_YUNXIN = "Yunxin";

	public static final String USER_ID = "user_id";
	public static final String LOGIN_TIME = "login_time";
	public static final String LOGOUT_TIME = "logout_time";
	public static final String DURATION = "duration";
	public static final String CHANNEL_ID = "channel_id";
	public static final String CLIENT_IP = "client_ip";
	public static final String NODE_IP = "node_ip";
	public static final String CLIENT = "client";

	public WsUserLoginLog init(Date now) {
		super.initTime(now);
		return this;
	}

	/** 计算区间内时长 */
	public long calcOnlineTime(@Nonnull TimeInterval interval, @Nullable Date next) {
		if (loginTime == null) {
			return 0L;
		}
		Date finalBegin = interval.getFinalBegin();
		Date finalEnd = interval.getFinalEnd();
		// 如果是当天，则直接以登录时间开始计算；如果不是当天，则以当天的开始时间为准
		finalBegin = loginTime.getTime() > finalBegin.getTime() || EasyDate.isSameDay(loginTime, finalBegin) ? loginTime : finalBegin;
		if (logoutTime == null) { // 没有登出时间
			logoutTime = next == null ? new Date(finalBegin.getTime() + TimeUnit.MINUTES.toMillis(5)) : next;
		}

		if (logoutTime.getTime() <= finalEnd.getTime()) { // 如果不跨天，则取登出时间；如果跨天，截止到当前结束
			finalEnd = logoutTime;
		}

		return finalEnd.getTime() - finalBegin.getTime();
	}

}
